package com.xianniu.ltc.aspect;

import cn.devezhao.persist4j.Query;
import cn.devezhao.persist4j.Record;
import cn.devezhao.persist4j.engine.ID;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rebuild.core.Application;
import com.rebuild.core.BootEnvironmentPostProcessor;
import com.rebuild.core.UserContextHolder;
import com.xianniu.ltc.enums.NicheWinRate;
import com.xianniu.ltc.mapper.RbShangjiMapper;
import com.xianniu.ltc.mapper.THuikuanjihuaMapper;
import com.xianniu.ltc.model.entity.THuikuanjihuaDTO;
import com.xianniu.ltc.model.entity.TProjectDetailDTO;
import com.xianniu.ltc.model.entity.TRbshangji4DTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author wangruijie
 * 实体新增/修改保存触发切面操作
 *
 */
@Slf4j
@Aspect
@Component
public class SaveInternalBeforeAspect {

    @Autowired
    private RbShangjiMapper rbShangjiMapper;
    @Resource
    private THuikuanjihuaMapper huikuanjihuaMapper;

    //拦截指定的方法,这里指只拦截TestService.getResultData这个方法
    @Pointcut("execution(public * com.rebuild.core.service.ServiceSpec.createOrUpdate(..))")
    public void excuteService() {

    }

    //执行方法前的拦截方法
    @Before("excuteService()")
    public void doBeforeMethod(JoinPoint joinPoint) {
        //获取目标方法的参数信息
        Object[] obj = joinPoint.getArgs();
        for (Object o : obj) {
            log.info("参数输出：{}", o);
            if (o instanceof Record) {
                Record record = (Record) o;
                // 过滤出 实体编码
                Integer entityCode = record.getEntity().getEntityCode();
                // 合同
                /*if (entityCode.equals(Integer.valueOf(992))){
                    log.info("商机转换为合同时，自动修改商机赢率为100%，状态修改为赢单TD开始:doSaleContract");
                    doSaleContract(record);
                    // 商机
                }else */
                if (entityCode.equals(Integer.valueOf(991))){
                    log.info("商机修改为输单后，最终确认时间字段值为当前时间开始：doNiche");
                    doNiche(record);
                }else if (entityCode.equals(Integer.valueOf(986))){
                    log.info("回款计划修改时，计算实际收款金额=计划收款金额-罚款金额");
                    doReceivablePlan(record);
                }
            }
        }
    }

    /**
     * 商机转换为合同时，自动修改商机赢率为100%，状态修改为赢单TD
     * @param data
     */
    private void doSaleContract(Record data){
        ID sjId = data.getID("shangjibianhao");
        if (sjId != null){
            // 根据商机ID查询商机
            QueryWrapper<TRbshangji4DTO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("RBSHANGJI4_ID", sjId.toString());
            // 根据条件查询商机列表
            int updateState = rbShangjiMapper.updateBySaleContract(sjId.toString(), NicheWinRate.case100.getValue());
            log.info("新增/修改销售合同（销售）的商机，触发修改商机赢率为赢单100%：{}",updateState);
        }
    }

    /**
     * 商机修改为输单后，最终确认时间字段值为当前时间
     * @param data
     */
    private void doNiche(Record data){
        ID winRate = data.getID("shangjijieduanyinglv");
        if (winRate != null){
            // 商机赢率为输单
            if (NicheWinRate.case00.getValue().equalsIgnoreCase(winRate.toString())){
                // 赋值最终确认时间为当前时间
                data.setDate("shangjiyingdanshijian", new Date());
                log.info(" 商机修改为输单后，最终确认时间字段值为当前时间开始");
            }
        }
    }

    /**
     * 回款计划修改时，计算实际收款金额=计划收款金额-罚款金额
     * @param data
     */
    private void doReceivablePlan(Record data){
        ID idStr = data.getPrimary();
        BigDecimal jihuashoukuanjine;
        BigDecimal fakuanjine;
        // 修改
        if (idStr != null){
            THuikuanjihuaDTO dto = huikuanjihuaMapper.selectById(idStr.toString());
            jihuashoukuanjine = data.getDecimal("jihuashoukuanjine")==null?dto.getJihuashoukuanjine():data.getDecimal("jihuashoukuanjine");
            fakuanjine = data.getDecimal("fakuanjine")==null?dto.getFakuanjine():data.getDecimal("fakuanjine");
            // 新增
        }else {
            jihuashoukuanjine = data.getDecimal("jihuashoukuanjine");
            fakuanjine = data.getDecimal("fakuanjine")==null?BigDecimal.ZERO:data.getDecimal("fakuanjine");
        }
        data.setDecimal("shijishoukuanjine78", jihuashoukuanjine.subtract(fakuanjine==null?BigDecimal.ZERO:fakuanjine));
    }

    /**
     * 校验字段是否已保存，避免二次保存（暂不使用）
     * @param record
     * @return
     */
    public Object checkIsExist(Record record){
        String sql = String.format("select count(fieldId) from metaField where belongEntity = ? and fieldName = ? and tenantCode = ? ");
        Query kehushu = Application.createQueryNoFilter(sql)
                .setParameter(1, record.getString("belongEntity"))
                .setParameter(2, record.getString("fieldName"))
                .setParameter(3, BootEnvironmentPostProcessor.getDefaultTenant());

        Object[] result = kehushu.unique();
        Object obj = Objects.isNull(result[0]) ? 0:result[0];
        return obj;
    }
}